package com.globalwave.common.web;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import org.springframework.scheduling.commonj.ScheduledTimerListener;
import org.springframework.scheduling.commonj.TimerManagerFactoryBean;

import commonj.timers.TimerManager;
import commonj.work.Work;
import commonj.work.WorkManager;

public class Test {
	WorkManager wm = null;
	TimerManager tm = null;
	
	public void test() throws Exception {

		try {
			Context ctx = new InitialContext();
			tm = (TimerManager) ctx.lookup("java:/comp/env/wm/FooTimerManager");
		}
		catch (NamingException e) {
			throw new Exception("failed to init", e);
		}
		
		try {
			//wm.schedule(new TestDaemon(), new TestWorkListener(0));
			ScheduledTimerListener listerner = new ScheduledTimerListener() ;
			listerner.setDelay(5000) ;
			listerner.setPeriod(5000) ;
			Runnable r = new Runnable(){
				int count = 0 ;
				@Override
				public void run() {
					// TODO Auto-generated method stub
					count++; 
					System.out.println("SampleRunnable running. Run number: " + count);

				}
				
			};
			listerner.setRunnable(r) ;
			/*
			TimerManagerFactoryBean factory = new TimerManagerFactoryBean() ;
			factory.setResourceRef(true) ;
			factory.setTimerManager(tm) ;
			factory.setScheduledTimerListeners(new ScheduledTimerListener[]{listerner}) ;
			factory.afterPropertiesSet() ;*/
			tm.schedule(listerner.getTimerListener(), 10000, 10000);
			//tm.schedule(listerner, 1000);
		}
		catch (Exception e) {
			throw new Exception(e.toString());
		}

	}
	public void test2() throws Exception {

		try {
			Context ctx = new InitialContext();
			wm = (WorkManager) ctx.lookup("java:/comp/env/wm/FooWorkManager");
		}
		catch (NamingException e) {
			throw new Exception("failed to init", e);
		}
		
		try {
			//wm.schedule(new TestDaemon(), new TestWorkListener(0));
			wm.schedule(new Work(){

				@Override
				public boolean isDaemon() {
					// TODO Auto-generated method stub
					return false;
				}

				@Override
				public void release() {
					// TODO Auto-generated method stub
					
				}

				@Override
				public void run() {
					// TODO Auto-generated method stub
					System.out.println(Thread.currentThread().getName() + " - running~~~");
					
					try {
						Thread.sleep(5*1000) ;
					} catch (InterruptedException e) {
						e.printStackTrace();
					}

					System.out.println(Thread.currentThread().getName() +  " - after 5min~~~");
					
				}
				
			});
		}
		catch (Exception e) {
			throw new Exception(e.toString());
		}

	}
}
